// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.ui.web.browser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dengues.ui.web.browser.dom.HTMLDocument;
import org.dengues.ui.web.browser.dom.HTMLElement;
import org.dengues.ui.web.browser.dom.Node;
import org.dengues.ui.web.browser.dom.NodeList;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;

/**
 * @author jliu
 */
public class LocationBinder {

    private final HTMLDocument document;

    /**
     * A map contains all elements and the location of this element;
     */
    private final Map<Rectangle, HTMLElement> bounds2element;

    /**
     * All element bounds, this can be very useful when retrieve element from a point .
     */
    private final List<Rectangle> boundsIndexs;

    /**
     * A cache contains all bounds retrieved.
     */
    private final Map<Point, Rectangle> boundsCache;

    /**
     * A <code>LocationBinder</code> class is used to calculate the bounds of all HTML Elements.
     */
    public LocationBinder(HTMLDocument document) {
        this.document = document;
        bounds2element = new HashMap<Rectangle, HTMLElement>();
        boundsIndexs = new ArrayList<Rectangle>();
        boundsCache = new HashMap<Point, Rectangle>();
    }

    /**
     * Calculate and save the locations.
     */
    public void saveLocations() {
        NodeList all = document.getAll();
        if (all != null) {
            int length = all.getLength();
            for (int i = 0; i < length; i++) {
                Node item = all.item(i);
                if (item instanceof HTMLElement) {
                    HTMLElement target = (HTMLElement) item;
                    Rectangle bounds = computeBounds(target);
                    target.setBounds(bounds);
                    boundsIndexs.add(bounds);
                    bounds2element.put(bounds, target);
                }
            }
        }
    }

    /**
     * Computing bounds for the HTML element.
     */
    public Rectangle computeBounds(HTMLElement target) {
        Rectangle bounds = new Rectangle(0, 0, 0, 0);
        int top = -1, left = -1;

        /** * Top and Left * */
        // 1 parent.offsetXX + parent.clientXX
        HTMLElement parent = target.getOffsetParent();
        while (parent != null) {
            top += parent.getOffsetTop();
            top += parent.getClientTop();
            top -= parent.getScrollTop();

            left += parent.getOffsetLeft();
            left += parent.getClientLeft();
            left -= parent.getScrollLeft();
            parent = parent.getOffsetParent();
        }
        // 2 offsetXX + clientXX
        top += target.getOffsetTop();
        top += target.getClientTop();

        left += target.getOffsetLeft();
        left += target.getClientLeft();

        // 3 scroll bar
        bounds.y = top;
        bounds.x = left;

        /** *Width and Height* */
        // : need some improvement...
        bounds.width = target.getOffsetWidth();
        bounds.height = target.getOffsetHeight();
        return bounds;
    }

    public HTMLElement getElementAt(Point anchor) {
        Rectangle bounds = boundsCache.get(anchor);
        if (bounds == null) {
            bounds = getAbsRectangle(anchor);
            boundsCache.put(anchor, bounds);
        }
        return bounds2element.get(bounds);
    }

    /**
     * Get a paint rectangle from given point, the return rectangle will contains the point, and this will return a
     * proper location. This would return a HTML HyperLink Element location firstly.
     */
    private Rectangle getAbsRectangle(Point anchor) {

        Map<HTMLElement, Rectangle> links2bounds = new HashMap<HTMLElement, Rectangle>();
        List<Rectangle> availableBounds = new ArrayList<Rectangle>();
        for (Rectangle bound : boundsIndexs) {
            if (bound.contains(anchor)) {
                HTMLElement elementImp = bounds2element.get(bound);
                if (elementImp != null) {
                    availableBounds.add(bound);
                    String nodeName = elementImp.getNodeName();
                    if (nodeName != null && ((nodeName.toUpperCase()).equals("A")))
                        links2bounds.put(elementImp, bound);
                }
            }
        }
        if (!links2bounds.isEmpty()) {
            return applyFilter(links2bounds.values());
        }
        return applyFilter(availableBounds);
    }

    /**
     * For paint, we will use a smallest rectangle which contains the given point.
     */
    private Rectangle applyFilter(Collection<Rectangle> availableBounds) {
        Rectangle result = null;
        for (Rectangle rectangle : availableBounds) {
            if (result == null) {
                result = rectangle;
            } else {
                result = rectangle.width < result.width || rectangle.height < result.height ? rectangle : result;
            }
        }
        return result;
    }

    public void clear() {
        bounds2element.clear();
        boundsCache.clear();
        boundsIndexs.clear();
    }
}
